package pgui.visual;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import pedrosm.utils.Debug;


/**
 * 
 * @author Pedro Silva Moreira
 */
public class PImage implements Cloneable {
	// Local Variables
	private BufferedImage imageBuffer;
	private ImageIcon imageIcon;
	private int x = 0, y = 0, width, height;

	// Creation
	public PImage() {
	}

	// Loading
	public void loadImage(String path) {
		try {
			setImageBuffer(ImageIO.read(new File(path)));
			updateImageIcon(getImageBuffer());
		} catch (Exception e) {
			Debug.debug("PImage", "Failed to load image: '" + path + "'");
		}
	}

	public void updateImageIcon(BufferedImage buffer) {
		setImageIcon(new ImageIcon(buffer));
		
		this.setWidth(buffer.getWidth());
		this.setHeight(buffer.getHeight());
	}
	
	public void resize(int nextWidth, int nextHeight) {
		BufferedImage resizedImage = new BufferedImage(nextWidth, nextHeight, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g = resizedImage.createGraphics();

		g.setComposite(AlphaComposite.Src);
		g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
				RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);

		g.drawImage(getImageBuffer(), 0, 0, nextWidth, nextHeight, null);
		g.dispose();
		
		updateImageIcon(resizedImage);
	}

	public void scale(float x, float y) {
		int nextWidth = (int) (getImageBuffer().getWidth() * x);
		int nextHeight = (int) (getImageBuffer().getHeight() * y);

		resize(nextWidth, nextHeight);
	}

	// Drawing
	public void draw(Graphics2D g) {
		if (getImageIcon() == null) {
			return;
		}

		g.drawImage(getImageIcon().getImage(), getX(), getY(), getWidth(),
				getHeight(), null);
	}

	// Get & Set
	public BufferedImage getImageBuffer() {
		return imageBuffer;
	}

	public void setImageBuffer(BufferedImage imageBuffer) {
		this.imageBuffer = imageBuffer;
	}

	public ImageIcon getImageIcon() {
		return imageIcon;
	}

	public void setImageIcon(ImageIcon imageIcon) {
		this.imageIcon = imageIcon;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public PImage instance() {
		try {
			return (PImage) this.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
		return null;
	}
}
